package com.example.sandbox.controller.order.pay58;

/**
 * 下游下单接口
 *
 * @Author Lierbao
 * @Date 2024/6/14 11:02
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.example.sandbox.controller.order.abstractController.AbstractPayOrderController;
import com.example.sandbox.controller.order.model.Brazil58OrderRequest;
import com.example.sandbox.controller.order.model.DownStreamConstant;
import com.example.sandbox.dto.*;
import com.example.sandbox.dto.Enum.ApiCodeEnum;
import com.example.sandbox.dto.Enum.Currency;
import com.example.sandbox.dto.Enum.Order58payStatus;
import com.example.sandbox.dto.domain.PayOrder;
import com.example.sandbox.helper.MchAndSignCheckHelper;
import com.example.sandbox.util.AmountUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.Random;

@Slf4j
@RestController
@Api(tags = "巴西支付下单接口")
public class Brazil58PayOrderController {
    private static final Random RANDOM = new Random();
    @Resource
    private MchAndSignCheckHelper mchAndSignCheckHelper;
    @Autowired
    private AbstractPayOrderController abstractPayOrderController;
    @PostMapping("/gateway/v1/pay/brazil/charge")
    @ResponseBody
    @ApiOperation("巴西支付IfCode下单接口")
    public ApiRes brazilIfCodeOrder(@RequestBody @Valid Brazil58OrderRequest request, HttpServletRequest httpRequest) {
        long startTime = System.currentTimeMillis();

        log.info("巴西支付IfCode下单接口入参 [{}]", JSON.toJSONString(request));
        // 验签
        MchRedisContext mchApp = mchAndSignCheckHelper.mch58AndSignAndIPCheckRedis(request, httpRequest, request.getNotifyUrl());

        // 装配请求
        GbpsdPayOrderRQ gbpsdPayOrderRQ = new GbpsdPayOrderRQ();
        gbpsdPayOrderRQ.setOrderId(gen58PayOrderId());
        gbpsdPayOrderRQ.setMchNo(request.getMerchantNo());
        gbpsdPayOrderRQ.setAppId(mchApp.getAppId());
        gbpsdPayOrderRQ.setMchOrderNo(request.getClientRequestId());
        // 金额转换
        gbpsdPayOrderRQ
                .setAmount(Long.parseLong(AmountUtil.convertDollar2Cent(request.getAmount(), Currency.BRL.getCurrency())));
        gbpsdPayOrderRQ.setCurrency(Currency.BRL.getCurrency());
        gbpsdPayOrderRQ.setClientIp("0.0.0.1");
        gbpsdPayOrderRQ.setSubject(request.getSubject());
        gbpsdPayOrderRQ.setBody(request.getBody());
        gbpsdPayOrderRQ.setNotifyUrl(request.getNotifyUrl());
        gbpsdPayOrderRQ.setExpiredTime(DownStreamConstant.EXPIRED_ORDER_SECONDS);

        // 支付成功跳转地址
        gbpsdPayOrderRQ.setReturnUrl("https://www.openx.com");
        JSONObject extParams = new JSONObject();
        extParams.put("debtorName", "");
        extParams.put("debtorDocumentNumber", "");
        gbpsdPayOrderRQ.setChannelExtra(extParams.toJSONString());
        // 是否需要拓展参数(返回URL), 默认1
        gbpsdPayOrderRQ.setNeedExtParam(null == request.getNeedExtParam() ? 1 : request.getNeedExtParam());

        // 目前自动分账
        gbpsdPayOrderRQ.setDivisionMode(PayOrder.DIVISION_MODE_AUTO);
        gbpsdPayOrderRQ.setExtParam(null);
        gbpsdPayOrderRQ.setReqTime(request.getReqTime() + "");
        gbpsdPayOrderRQ.setVersion(DownStreamConstant.VERSION);
        gbpsdPayOrderRQ.setSign(request.getSign());
        gbpsdPayOrderRQ.setSignType(DownStreamConstant.SIGN_TYPE);
        // 移除 wayCode, 此处改为 ifCode
        ApiRes apiRes = abstractPayOrderController.unifiedOrderIfCode(CS.IF_CODE.BRAZIL_PAY, gbpsdPayOrderRQ);

        if (null == apiRes) {
            return apiRes;
        }
        // 业务错误直接返回
        if (!Objects.isNull(apiRes.getCode()) && ApiCodeEnum.SUCCESS.getCode() != apiRes.getCode()) {
            log.info("[{}]支付下单链路耗时: [{}]ms", request.getClientRequestId(), System.currentTimeMillis() - startTime);
            return apiRes;
        }

        UnifiedOrderRS data = (UnifiedOrderRS) apiRes.getData();
        if (null == data) {
            return apiRes;
        }
        // 序列化对象并解析回 JSON 对象
        String jsonString = JSON.toJSONString(data, SerializerFeature.WriteMapNullValue);
        JSONObject jsonRetMsg = JSON.parseObject(jsonString);
        jsonRetMsg.remove("channelRetMsg");
        jsonRetMsg.put("orderState", Order58payStatus.getValueByKey(data.getOrderState()));
        ApiRes<Object> ok = ApiRes.ok(jsonRetMsg);
        ok.setSign(apiRes.getSign());
        // stopWatch.stop();
        log.info("[{}]支付下单链路耗时: [{}]ms", request.getClientRequestId(), System.currentTimeMillis() - startTime);

        return ok;
    }
    public static String gen58PayOrderId() {

        // 生成时间戳
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());

        // 生成随机数部分
        long randomPart = RANDOM.nextInt(100000000); // 生成一个9位随机数

        return String.format("%s%s%09d", "I", timestamp, randomPart);
    }
}
